import React from 'react';

import { cn } from './cn';

/**
 * Set default props with `React.forwardRef`.
 *
 * - Use `withCn` if only setting `className`
 */
export function withProps<T extends React.ElementType>(
  Component: T,
  defaultProps: Partial<React.ComponentPropsWithoutRef<T>>
) {
  const ComponentWithClassName = Component as React.FC<{ className?: string }>;

  return React.forwardRef<
    React.ComponentRef<T>,
    React.ComponentPropsWithoutRef<T>
  >(function ExtendComponent(props, ref) {
    const newProps: any = { ...defaultProps, ...props };
    const className = cn(
      (defaultProps as any).className,
      (props as any).className
    );

    if (className) {
      newProps.className = className;
    }

    return <ComponentWithClassName ref={ref} {...newProps} />;
  });
}
